<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @add="addFn"></TodoHeader>

    <!-- 主体部分 -->
    <TodoBody :list="showList"
     @delList="delList" 
     @change="changeFn"
     @isCheckchange="isCheckchange"></TodoBody>

    <!-- 底部部分 -->
     <TodoFooter :list="list" 
     @clearList="clearList" 
      :isDoneAll="isDoneAll" 
      :type="type"
      @changeType='changeType'></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoBody from '@/components/TodoBody.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  components:{
    TodoHeader,
    TodoBody,
    TodoFooter,
  },
 data () {
  return {
    type:'all',
    list: JSON.parse(localStorage.getItem('list')) || [
      { id: 1, name: '吃饭', isDone: true },
      { id: 2, name: '睡觉', isDone: false },
      { id: 3, name: '打豆豆', isDone: true }
    ]
  }
},
methods:{
  //删除事件
   delList(id){
     this.list= this.list.filter(item =>item.id !==id)
   },
   //修改事件
   changeFn(id){
        this.list.forEach(item =>{
           if(item.id ===id) item.isDone =!item.isDone
        })

   },
   //添加事件
   addFn(name){
      const obj ={id: +new Date(), name: name, isDone: false}
        this.list= [obj,...this.list]
   },
   //清除所有已完成的
   clearList(){
      this.list = this.list.filter(item =>item.isDone ===false)

   },
   //选项按钮
   changeType(type){
    this.type =type
   },
   //全选按钮
   isCheckchange(flag){
     this.list.forEach(item => item.isDone =flag)
   }
},
computed:{
   isDoneAll(){
      return this.list.some(item =>item.isDone)
     },
     showList(){
        switch (this.type) {
          case 'all':
            return this.list
             case 'active':
            return this.list.filter(item => !item.isDone)
             case 'completed':
            return this.list.filter(item => item.isDone)
          default: 
            return this.list
        }
     },

},
watch:{
   list:{
       deep:true ,
       handler(newVal){
         localStorage.setItem('list',JSON.stringify(newVal))
       }
   }
}
}
</script>

<style></style>
